package com.rbac.admin.controller.system;

import com.rbac.admin.annotation.OperationLog;
import com.rbac.admin.common.result.Result;
import com.rbac.admin.entity.system.SystemDept;
import com.rbac.admin.service.system.DeptService;
import com.rbac.admin.vo.system.DeptVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 部门管理控制器
 *
 * @author rbac-admin
 * @since 2024-07-18
 */
@RestController
@RequestMapping("/system/depts")
@Tag(name = "部门管理", description = "部门管理相关接口")
public class DeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 查询部门列表
     */
    @Operation(summary = "查询部门列表")
    @OperationLog(module = "部门管理", type = "查询", value = "查询部门列表")
    @GetMapping
    public Result<List<DeptVO>> getDeptList(
            @Parameter(description = "部门名称") @RequestParam(required = false) String deptName,
            @Parameter(description = "部门编码") @RequestParam(required = false) String deptCode,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            // 构建查询条件
            SystemDept dept = new SystemDept();
            dept.setDeptName(deptName);
            dept.setDeptCode(deptCode);
            dept.setStatus(status);
            
            // 查询部门列表
            List<DeptVO> deptList = deptService.getDeptList(dept);
            
            return Result.success(deptList);
        } catch (Exception e) {
            return Result.failed("查询部门列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询部门树结构
     */
    @Operation(summary = "查询部门树结构")
    @OperationLog(module = "部门管理", type = "查询", value = "查询部门树结构")
    @GetMapping("/tree")
    public Result<List<DeptVO>> getDeptTree(
            @Parameter(description = "部门名称") @RequestParam(required = false) String deptName,
            @Parameter(description = "部门编码") @RequestParam(required = false) String deptCode,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            // 构建查询条件
            SystemDept dept = new SystemDept();
            dept.setDeptName(deptName);
            dept.setDeptCode(deptCode);
            dept.setStatus(status);
            
            // 查询部门树
            List<DeptVO> deptTree = deptService.getDeptTree(dept);
            
            return Result.success(deptTree);
        } catch (Exception e) {
            return Result.failed("查询部门树失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取部门详情
     */
    @Operation(summary = "获取部门详情")
    @OperationLog(module = "部门管理", type = "查询", value = "查看部门详情")
    @GetMapping("/{id}")
    public Result<DeptVO> getDeptById(@Parameter(description = "部门ID") @PathVariable int id) {
        try {
            DeptVO dept = deptService.getDeptById(id);
            if (dept == null) {
                return Result.failed("部门不存在");
            }
            return Result.success(dept);
        } catch (Exception e) {
            return Result.failed("获取部门详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户列表（用于部门负责人选择）
     */
    @Operation(summary = "获取用户列表")
    @GetMapping("/users")
    public Result<List<Map<String, Object>>> getUserList() {
        try {
            List<Map<String, Object>> userList = deptService.getUserList();
            return Result.success(userList);
        } catch (Exception e) {
            return Result.failed("获取用户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建部门
     */
    @Operation(summary = "创建部门")
    @OperationLog(module = "部门管理", type = "新增", value = "新增部门", recordParams = true, recordResult = true)
    @PostMapping
    public Result<SystemDept> createDept(@RequestBody SystemDept dept) {
        try {
            // 检查部门名称是否已存在
            if (deptService.checkDeptNameExists(dept.getDeptName(), null)) {
                return Result.failed("部门名称已存在");
            }
            
            // 检查部门编码是否已存在
            if (deptService.checkDeptCodeExists(dept.getDeptCode(), null)) {
                return Result.failed("部门编码已存在");
            }
            
            // 设置默认值
            dept.setCreateTime(LocalDateTime.now());
            dept.setUpdateTime(LocalDateTime.now());
            dept.setDeleteFlag(0);
            
            boolean success = deptService.save(dept);
            if (success) {
                return Result.success("创建成功", dept);
            } else {
                return Result.failed("创建失败");
            }
        } catch (Exception e) {
            return Result.failed("创建部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新部门
     */
    @Operation(summary = "更新部门")
    @OperationLog(module = "部门管理", type = "修改", value = "修改部门信息", recordParams = true, recordResult = true)
    @PutMapping("/{id}")
    public Result<Boolean> updateDept(
            @Parameter(description = "部门ID") @PathVariable int id,
            @RequestBody SystemDept dept) {
        try {
            // 检查部门是否存在
            SystemDept existDept = deptService.getById(id);
            if (existDept == null) {
                return Result.failed("部门不存在");
            }
            
            // 检查部门名称是否已存在（排除自身）
            if (deptService.checkDeptNameExists(dept.getDeptName(), id)) {
                return Result.failed("部门名称已存在");
            }
            
            // 检查部门编码是否已存在（排除自身）
            if (deptService.checkDeptCodeExists(dept.getDeptCode(), id)) {
                return Result.failed("部门编码已存在");
            }
            
            // 设置ID和更新时间
            dept.setId(id);
            dept.setUpdateTime(LocalDateTime.now());
            
            boolean success = deptService.updateById(dept);
            if (success) {
                return Result.success("更新成功", true);
            } else {
                return Result.failed("更新失败");
            }
        } catch (Exception e) {
            return Result.failed("更新部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除部门
     */
    @Operation(summary = "删除部门")
    @OperationLog(module = "部门管理", type = "删除", value = "删除部门", recordParams = true)
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteDept(@Parameter(description = "部门ID") @PathVariable int id) {
        try {
            // 检查部门是否存在
            SystemDept dept = deptService.getById(id);
            if (dept == null) {
                return Result.failed("部门不存在");
            }
            
            // 检查是否有子部门
            if (deptService.hasChildDept(id)) {
                return Result.failed("存在子部门，不能删除");
            }
            
            // 检查是否有用户
            if (deptService.hasUserByDept(id)) {
                return Result.failed("部门下存在用户，不能删除");
            }
            
            // 逻辑删除部门
            boolean success = deptService.removeById(id);
            if (success) {
                return Result.success("删除成功", true);
            } else {
                return Result.failed("删除失败");
            }
        } catch (Exception e) {
            return Result.failed("删除部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改部门状态
     */
    @Operation(summary = "修改部门状态")
    @OperationLog(module = "部门管理", type = "修改", value = "修改部门状态", recordParams = true)
    @PutMapping("/{id}/status")
    public Result<Boolean> changeDeptStatus(
            @Parameter(description = "部门ID") @PathVariable int id,
            @RequestBody SystemDept statusDept) {
        try {
            // 检查部门是否存在
            SystemDept dept = deptService.getById(id);
            if (dept == null) {
                return Result.failed("部门不存在");
            }
            
            // 修改状态
            dept.setStatus(statusDept.getStatus());
            dept.setUpdateTime(LocalDateTime.now());
            
            boolean success = deptService.updateById(dept);
            if (success) {
                return Result.success("状态修改成功", true);
            } else {
                return Result.failed("状态修改失败");
            }
        } catch (Exception e) {
            return Result.failed("修改部门状态失败：" + e.getMessage());
        }
    }
} 